package Lee_code;

import java.util.HashMap;

/**
 * @author blh
 * @date 2024年08月07日 18:39
 */
public class Lee_525_87_2 {
    int res = 0;

    public int findMaxLength(int[] nums) {

        // 1和0的差值(1-0)
        int diff = 0;
        // 数组下标 - 1和0的差值(1-0)
        HashMap<Integer, Integer> prefix = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                diff--;
            } else {
                diff++;
            }
            prefix.putIfAbsent(diff, i);
            if (prefix.containsKey(diff - 1)) {
                res = Math.max(res, i - prefix.get(diff - 1) + 1);
            }
        }
        return res;
    }
}
